package com.shanzmoo.platform.manage.api.manager.product;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.util.CollectionUtil;
import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.db.module.product.domain.dto.*;
import com.shanzmoo.db.module.product.domain.query.ProductQueryVO;
import com.shanzmoo.db.module.product.domain.vo.BrandVO;
import com.shanzmoo.db.module.product.domain.vo.ProductVO;
import com.shanzmoo.db.module.product.entity.ProductPictureEntity;
import com.shanzmoo.db.module.product.entity.ProductSkuEntity;
import com.shanzmoo.db.module.product.entity.ProductSpuEntity;
import com.shanzmoo.db.module.product.service.*;
import com.shanzmoo.platform.manage.api.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 商品spumanager
 * @author xueqz
 */
@Component
@RequiredArgsConstructor
public class ProductSpuManager {

    @Autowired
    private IProductSpuService productSpuService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IProductPictureService productPictureService;

    public SHttpResponse<PageRespBase<ProductVO>> getSpuList(ProductQueryVO productQueryVO) {
        // 开启分页
        IPage<ProductVO> productVOIPage = productSpuService.getSpuList(productQueryVO);
        for (ProductVO productVO : productVOIPage.getRecords()) {
            if(StringUtils.isNotBlank(productVO.getCategoryName1())){
                String categoryNames = productVO.getCategoryName1();
                String[] names = categoryNames.split(",");
                if(names.length != 3) {
                    SResponse.fail(Constant.ERRCODE_PRODUCT_CATEGORYIDLENGTH, "错误商品分类级别:"+names.length);
                }
                productVO.setCategoryName1(names[0]);
                productVO.setCategoryName2(names[1]);
                productVO.setCategoryName3(names[2]);
            }else{
                SResponse.fail(Constant.ERRCODE_PRODUCT_CATEGORYNAME, "商品分类名未找到");
            }
        }
        PageRespBase<ProductVO> re = PageRespBase.create(productVOIPage, productVOIPage.getRecords());
        return SHttpResponse.ok(re);
    }

    public SHttpResponse<Boolean> operationSpu(Integer id, Boolean shelvesMark) {
        ProductSpuEntity productSpuEntity = new ProductSpuEntity();
        productSpuEntity.setId(id);
        productSpuEntity.setUpdateUser(SecurityUtil.getCurrentUserId());
        productSpuEntity.setUpdateTime(LocalDateTime.now());
        productSpuEntity.setShelves(shelvesMark);
        productSpuService.updateById(productSpuEntity);
        return SHttpResponse.ok();
    }

    /**
     * 保存spu和sku信息
     * @param productSaveDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SHttpResponse<Boolean> saveSpu(ProductSaveDto productSaveDto) {
        //保存spu
        SpuSaveDto spuSaveDto = productSaveDto.getSpuSaveDto();
        ProductSpuEntity data = spuSaveDto.convert(ProductSpuEntity.class);
        data.setSpu(UUID.randomUUID().toString());
        data.setCreateUser(SecurityUtil.getCurrentUserId());
        productSpuService.save(data);
        //保存sku
        List<SkuSaveDto> skuSaveDtoList = productSaveDto.getSkuSaveDtoList();
        List<ProductSkuEntity> skuList = CollectionUtil.convert(skuSaveDtoList, ProductSkuEntity.class);
        skuList.stream().forEach(r -> {
            r.setParentId(data.getId());
            r.setSku(UUID.randomUUID().toString());
            r.setCreateUser(SecurityUtil.getCurrentUserId());
        });
        productSkuService.saveBatch(skuList);
        //处理图片信息
        handlerPicture(data.getId(),productSaveDto.getMainPictureList(),productSaveDto.getInfoPictureList());
        return SHttpResponse.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public SHttpResponse<Boolean> updateSpu(ProductUpdateDto productUpdateDto) {
        //更新spu
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        SpuUpdateDto spuUpdateDto = productUpdateDto.getSpuUpdateDto();
        ProductSpuEntity data = spuUpdateDto.convert(ProductSpuEntity.class);
        data.setUpdateUser(currentUserId);
        productSpuService.updateById(data);
        //更新sku
        List<SkuUpdateDto> skuUpdateDtoList = productUpdateDto.getSkuUpdateDtoList();
        List<ProductSkuEntity> skuList = CollectionUtil.convert(skuUpdateDtoList, ProductSkuEntity.class);
        for (ProductSkuEntity productSkuEntity : skuList) {
            if(productSkuEntity.getId() != null){
                //更新
                productSkuEntity.setUpdateUser(currentUserId);
                productSkuService.updateById(productSkuEntity);
            }else{
                //插入
                productSkuEntity.setParentId(data.getId());
                productSkuEntity.setSku(UUID.randomUUID().toString());
                productSkuEntity.setCreateUser(currentUserId);
                productSkuService.save(productSkuEntity);
            }
        }
        //删除前端返回不存在,后端存在的sku
        List<Integer> productNoList = skuList.stream().map(ProductSkuEntity::getId).collect(Collectors.toList());
        productSpuService.flagWaitDeleteSku(data.getId(),productNoList);
        //处理图片信息
        handlerPicture(data.getId(),productUpdateDto.getMainPictureList(),productUpdateDto.getInfoPictureList());
        return SHttpResponse.ok();
    }

    /**
     * 处理图片信息
     */
    private void handlerPicture(Integer id,List<ProductPictureEntity> mainPictureList,List<ProductPictureEntity> infoPictureList){
        //先删除spu关联的详情图和商品图
        productPictureService.update(new UpdateWrapper<ProductPictureEntity>().eq("product_id",id).set("deleted",true));
        //新增商品详情
        if(CollUtil.isNotEmpty(mainPictureList)){
            mainPictureList.stream().forEach(r -> {
                r.setProductId(id);
                r.setCreateUser(SecurityUtil.getCurrentUserId());
            });
            productPictureService.saveBatch(mainPictureList);
        }
        if(CollUtil.isNotEmpty(infoPictureList)){
            //新增商品图片
            infoPictureList.stream().forEach(r -> {
                r.setCreateUser(SecurityUtil.getCurrentUserId());
                r.setProductId(id);
            });
            productPictureService.saveBatch(infoPictureList);
        }
    }

    public SHttpResponse<Map> getStaticProductData() {

        return SHttpResponse.ok();
    }

    public SHttpResponse<ProductUpdateDto> getSpuDetailBySpuId(Integer spuId) {
        ProductUpdateDto productUpdateDto = new ProductUpdateDto();
        ProductSpuEntity spuEntity = productSpuService.getById(spuId);
        SpuUpdateDto spuUpdateDto = BeanUtil.toBean(spuEntity, SpuUpdateDto.class);
        productUpdateDto.setSpuUpdateDto(spuUpdateDto);
        List<ProductSkuEntity> skuList = productSkuService.list(new QueryWrapper<ProductSkuEntity>().eq("deleted", false).eq("parent_id",spuId));
        List<SkuUpdateDto> list = CollectionUtil.convert(skuList, SkuUpdateDto.class);
        productUpdateDto.setSkuUpdateDtoList(list);
        List<ProductPictureEntity> mainList = productPictureService.list(new QueryWrapper<ProductPictureEntity>()
                .eq("deleted", false).eq("product_id",spuId).eq("picture_type", "main"));
        productUpdateDto.setMainPictureList(mainList);
        List<ProductPictureEntity> infoList = productPictureService.list(new QueryWrapper<ProductPictureEntity>()
                .eq("deleted", false).eq("product_id",spuId).eq("picture_type", "info"));
        productUpdateDto.setInfoPictureList(infoList);
        return SHttpResponse.ok(productUpdateDto);
    }
}
